const { v4: uuidv4 } = require('uuid');
class RoomService {
  constructor() {
    this.rooms = new Map();
    this.usedRoomNumbers = new Set(); // 跟踪使用过的房间号
    this.userIds = new Set();
  }

  async generateRoomNumber() {
    // 确保房间号唯一
    let attempts = 0;
    const maxAttempts = 10;
    
    while (attempts < maxAttempts) {
      // 生成8位数字房间号
      const timestamp = Date.now().toString().slice(-2); // 后4位时间戳
      const random = Math.floor(1000 + Math.random() * 9000); // 4位随机数
      const roomNumber = `${timestamp}${random}`;
      
      // 检查是否已存在
      if (!this.rooms.has(roomNumber)) {
        return roomNumber;
      }
      
      attempts++;
    }
    
    throw new Error('无法生成唯一房间号，请稍后重试');
  }

  async createRoom(nickname) {
    const roomNumber = await this.generateRoomNumber();
    const userId = uuidv4(); 
    const room = {
      roomNumber,
      players: [{
        id:userId,
        nickname:nickname,
        isReady:false
        }
      ],
      status: 'waiting',
      createdAt: new Date(),
      owner: userId,
      expireAt: new Date(Date.now() + 24 * 60 * 60 * 1000) // 24小时后过期
    };
    
    this.rooms.set(roomNumber, room);
    return room;
  }

  async joinRoom(roomNumber, nickname) {
    const room = this.rooms.get(roomNumber);
    if (!room) {
      throw new Error('房间不存在');
    }
    if (room.players.length >= 3) {
      throw new Error('房间已满');
    }

    // 为新加入的玩家生成 userId
    const userId = uuidv4();
    
    const newPlayer = {
      id: userId,
      nickname: nickname,
      isReady: false
    };
    
    room.players.push(newPlayer);
    return room;
  }

  async updatePlayerReady(roomNumber, userId, isReady) {
    const room = this.rooms.get(roomNumber);
    if (!room) {
      throw new Error('房间不存在');
    }
    const player = room.players.find(p => p.id === userId);
    if (player) {
      player.isReady = isReady;
    }
    return room;
  }

  // 添加清理过期房间的方法
  cleanExpiredRooms() {
    const now = new Date();
    for (const [roomNumber, room] of this.rooms.entries()) {
      if (room.expireAt < now || (room.status === 'waiting' && room.players.length === 0)) {
        this.rooms.delete(roomNumber);
      }
    }
  }

  // 获取房间信息
  async getRoom(roomNumber) {
    const room = this.rooms.get(roomNumber);
    if (!room) {
      throw new Error('Room not found');
    }
    return room;
  }

  updatePlayerOnlineStatus(roomNumber, userId, isOnline) {
    const room = this.rooms.get(roomNumber);
    if (!room) return;

    const player = room.players.find(p => p.id === userId);
    if (player) {
      player.isOnline = isOnline;
      // 广播在线状态更新
      this.broadcastToRoom(roomNumber, {
        type: 'ONLINE_STATUS_UPDATE',
        payload: { userId, isOnline }
      });
    }
  }
}

module.exports = new RoomService(); 
// export default new RoomService();